<template>
  <view class="map">
    <!-- color：主题色 addressList:地址管理数据 @chooseClick：选择事件 @editClick：编辑事件  -->
    <cc-addressSet
      v-if="addressList.length"
      :colors="colors"
      :addressList="addressList"
      :currentId="addressList[0]._id"
      @chooseClick="chooseClick"
      @editClick="editClick"
      @chooseDelete="chooseDelete"
    ></cc-addressSet>

    <view class="save">
      <view
        class="btn flex flex-item-center"
        :style="'background:' + colors"
        @click="$jump('/subPages/user/map/create-map')"
      >
        <u-icon name="plus" color="#fff"></u-icon>
        <view style="margin-left: 20rpx">添加收货地址</view>
      </view>
    </view>
  </view>
</template>

<script>
import { getModelList, deleteModel, updateModel } from "@/api";
import constants from "@/common/constants";
export default {
  data() {
    return {
      addressList: [],
      colors: "#C94117",
      firstId: "",
    };
  },
  computed: {},
  methods: {
    // 选择地址
    async chooseClick(item) {
      await updateModel(
        "65c1d9085efd5153ff55e6f4",
        {
          ...item,
          isDefault: Date.now(),
        },
        item._id
      );

      await this.getAddressList();
    },
    // 编辑地址
    editClick(item) {
      uni.navigateTo({
        url: `/subPages/user/map/create-map?addressId=${item._id}&firstId=${this.firstId}`,
      });
    },
    // 删除地址
    async chooseDelete(item) {
      console.log("delete", item);
      const res = await deleteModel("65c1d9085efd5153ff55e6f4", item._id);
      if (res.code === 200) {
        await this.getAddressList();
        uni.showToast({
          title: "删除成功~",
          icon: "none",
        });
      }
    },
    // 获取地址列表数据
    async getAddressList() {
      let sortData = {
        currentPage: 1,
        pageSize: -1,
        sort: {
          isDefault: "desc",
        },
      };
      const res = await getModelList("65c1d9085efd5153ff55e6f4", sortData);
      if (res.code === 200) {
        this.addressList = res.data?.list.map((item) => {
          item.moreAddress = item.addressDetail;
          return item;
        });

        this.firstId = this.addressList?.[0]?._id;
      }
    },
  },
  async onShow() {
    await this.getAddressList();
  },
  onLoad() {
    // 获取主题色
    this.colors = constants.THEME_COLOR;
  },
};
</script>

<style lang="scss" scoped>
.save {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 120upx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.save view {
  display: flex;
}

.save .btn {
  box-shadow: 0upx 5upx 10upx rgba(0, 0, 0, 0.4);
  width: 80%;
  height: 80upx;
  border-radius: 80upx;
  background-color: #f23a3a;
  color: #fff;
  justify-content: center;
  align-items: center;
  font-size: 30upx;
  margin-bottom: 60px;

  &:active {
    transform: scale(0.98);
  }
}
</style>
